package org.jvm.instruction.references.array.newarray;

import org.jvm.instruction.base.*;
import org.jvm.rtda.Object;
import org.jvm.rtda.heap.Klass;
import org.jvm.rtda.heap.symref.ClassRef;
import org.jvm.rtda.thread.*;

/**
 * 创建多维数组
 *
 * @author 海燕
 * @date 2023/2/14
 */
public class MULTI_ANEW_ARRAY implements Instruction {

    /**
     * 指向类常量池中的类符号引用，类符号引用就是多维数组类
     */
    private int index;
    /**
     * 数组维度
     */
    private int dimensions;

    @Override
    public void fetchOperands(ByteCodeReader reader) {
        this.index = reader.readUint16();
        this.dimensions = reader.readUint8();
    }

    @Override
    public void execute(Frame frame) {
        //解析数组的成员类型，根据成员类型的类名拼接数组类名
        ClassRef classRef = (ClassRef) frame.getMethod().getKlass().getConstantPool().getConstant(this.index);
        Klass arrayClass = classRef.resolvedClass(frame.getThread());
        OperandStack operandStack = frame.getOperandStack();
        //每个维度的数组长度
        int[] counts = new int[dimensions];
        //连续pop dimensions次，获取每个dimensions的长度，并检查是否小于0
        for (int i = 0; i < dimensions; i++) {
            counts[dimensions - 1 - i] = operandStack.popInt();
        }
        Object arrObject = InstructionUtil.newMultDimensionalArray(0, counts, arrayClass);
        operandStack.pushRef(arrObject);
    }
}
